package com.java.business.system.common.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.java.business.system.permis.bean.User;
import com.java.business.system.permis.service.UserService;
import com.java.core.bean.ResultBean;
import com.java.core.utils.ResponseUtils;
import com.java.core.utils.SessionUtils;

@Controller
public class LoginController {

	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	public void login(HttpServletRequest request, HttpServletResponse response,
			User user) {
		ResultBean rb = new ResultBean();
		try {
			User dbUser = userService.getUserByUserName(user.getUsername());
			if (dbUser != null) {
				if (user.getPassword().equals(dbUser.getPassword())) {
					SessionUtils.setSessionUser(request, dbUser);
				} else {
					rb.setMsg("密码错误！");
					rb.setSuccess(false);
				}
			} else {
				rb.setMsg("用户名不存在！");
				rb.setSuccess(false);
			}
		} catch (Exception e) {
			rb.setSuccess(false);
			rb.setMsg(e.getMessage());
		}
		ResponseUtils.renderJson(response, JSON.toJSONString(rb));
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		SessionUtils.removeSessionUser(request);
		return "/login";
	}
}
